package com.mingmen.canting.jingli;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mingmen.canting.R;
import com.mingmen.canting.adapter.MyLabelAdapter;
import com.mingmen.canting.dialog.ButtomDialogView;
import com.mingmen.canting.http.MyOkhttp;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.AppConfig;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.BeiZhuModel;
import com.mingmen.canting.model.LinkLabelBean;
import com.mingmen.canting.model.ObjectResult;
import com.mingmen.canting.model.ShopListModel;
import com.mingmen.canting.model.SubMitModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.util.ToolList;
import com.mingmen.canting.zhenbanlibrary.ClassifyNewAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class JingLiSortDetailFragment extends Fragment implements ClassifyNewAdapter.OnItemClickListener {
    private RecyclerView mRv;
    private ClassifyNewAdapter mAdapter;


    TextView tv_total;
    CheckBox cb_check;
    RecyclerView recycle_liebiao;

    //    List<MyGoodsInfo> myGoodsInfos = new ArrayList<>();
//    MyGoodsInfo myGoodsInfo;
    LinearLayoutManager linearLayoutManager;
    private String[] str = new String[]{"标题1", "帅哥", "校园", "军事", "悬疑", "科幻"};
    private LinkLabelBean linkLabelBean;

    RecyclerView recycle_biaoqian;
    private List<LinkLabelBean> list = new ArrayList<>();
    Button btn_submit;
    TextView text_del;
    List<ShopListModel.DataBean> data = new ArrayList<>();
    private List<String> mystrList = new ArrayList<>();
    String token;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sort_detail2, null);
        mRv = (RecyclerView) view.findViewById(R.id.rv);
        tv_total = (TextView) view.findViewById(R.id.tv_total);
        cb_check = (CheckBox) view.findViewById(R.id.cb_check);
        recycle_liebiao = view.findViewById(R.id.recycle_liebiao);
        recycle_biaoqian = view.findViewById(R.id.recycle_biaoqian);
        btn_submit = view.findViewById(R.id.btn_submit);
        text_del = view.findViewById(R.id.text_del);
        Log.d("dkdkkd", "到这里了么");
        String string = getArguments().getString("right");
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        for (int i = 0; i < mVals.length; i++) {
            mystrList.add(mVals[i]);
        }
        Gson gson = new Gson();
        ShopListModel shopListModel = new ShopListModel();
        shopListModel = gson.fromJson(string, ShopListModel.class);
        data = shopListModel.getData();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        System.out.println(formatter.format(date));
//        date_Send = formatter.format(date);
        Date date3 = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date3);
        calendar.add(Calendar.DATE, 1);//1表示明天,-1表示昨天
        date3 = calendar.getTime(); //这个时间就是明天
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter2.format(date3);
        System.out.println(dateString);
        Log.d("dateStringdateString", dateString);
        date_Send = dateString;


        Log.d("到这里了么", string);

        linearLayoutManager = new LinearLayoutManager(getActivity());
        recycle_liebiao.setLayoutManager(linearLayoutManager);


        mAdapter = new ClassifyNewAdapter(getActivity(), data);

        recycle_liebiao.setAdapter(mAdapter);
        mAdapter.setDataList(data);

        mAdapter.setOnItemClickListener(this);
        cb_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    if (cb_check.isChecked()) {

                        for (int i = 0; i < data.size(); i++) {
                            if (data.get(i).getApplyAmount() == 0) {
                                data.get(i).setChecked(false);
                            } else {
                                if (!applyList.isEmpty()) {
                                    applyList.clear();
                                }

                                data.get(i).setChecked(true);
                                text_del.setVisibility(View.VISIBLE);
                                JSONObject jsonObject = new JSONObject();
                                try {
                                    jsonObject.put("commodityId", data.get(i).getCommodityId());
                                    jsonObject.put("commodityAmount", data.get(i).getApplyAmount() + "");
                                    jsonObject.put("categoryId", "0");
                                    jsonObject.put("mark", data.get(i).getMark());
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                applyList.add(jsonObject.toString());
                                ToolList.removeDuplicateWithOrder(applyList);
                            }
                        }
                        Log.d("AllSelectAllApplist", applyList.toString());
//                        showTotalPrice();
                        tv_total.setText("已选购" + applyList.size() + "");
                        mAdapter.notifyDataSetChanged();


                    }
                } else {
                    for (int i = 0; i < data.size(); i++) {
                        data.get(i).setChecked(false);
                    }
//                    showTotalPrice();
                    applyList.clear();
                    mAdapter.notifyDataSetChanged();
                    Log.d("NoSelectAllApplist", applyList.toString());
                    tv_total.setText("已选购" + applyList.size() + "");
                }
            }
        });

        for (int i = 0; i < str.length; i++) {
            linkLabelBean = new LinkLabelBean();
            linkLabelBean.setStr(str[i]);
            list.add(linkLabelBean);
        }
        final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
        mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int type = recycle_biaoqian.getAdapter().getItemViewType(position);//获得返回值

                if (type == 99) {
                    return mLayoutManager.getSpanCount();
                } else {
                    return 1;
                }
            }
        });
        recycle_biaoqian.setLayoutManager(mLayoutManager);
        MyLabelAdapter linkLabelAdapter = new MyLabelAdapter(getActivity());
        recycle_biaoqian.setAdapter(linkLabelAdapter);
        linkLabelAdapter.setDataList(mystrList);
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.custom_divider));

        recycle_biaoqian.addItemDecoration(divider);
        linkLabelAdapter.setOnItemClickListener(new MyLabelAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int pos, List<String> myLiveList) {
                Toast.makeText(getActivity(), mystrList.get(pos), Toast.LENGTH_SHORT).show();
                linkLabelAdapter.setCheckedPosition(pos);
            }

        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                public static String DAISHENHE="restaurant/apply/getApplyBillList";
                String token = (String) SharePreferenceUtil.get(getActivity(), "token", "");

                List<String> mylist = new ArrayList<>();

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("commodityId", "商品1");
                    jsonObject.put("commodityAmount", "10");
                    jsonObject.put("categoryId", "0");
                    jsonObject.put("mark", "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                JSONObject jsonObject2 = new JSONObject();
                try {
                    jsonObject2.put("commodityId", "商品1");
                    jsonObject2.put("commodityAmount", "10");
                    jsonObject2.put("categoryId", "0");
                    jsonObject2.put("mark", "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mylist.add(jsonObject.toString());
                mylist.add(jsonObject2.toString());
                Log.d("mylistmylistmylist", "dkdkdk");
                Log.d("DKkdkdkdk", jsonObject.toString());

//                [{"commodityId":"商品1","commodityAmount":"10","categoryId":"0","mark":""}, {"commodityId":"商品1","commodityAmount":"10","categoryId":"0","mark":""}]

//                @"8点之前",@"8~10点",@"10~12点",@"12~14点",@"14~16点",@"16~18点",@"18点之后applyList

                HttpResponse.submitData(token, date_Send, "3", applyList.toString(), "0", new StringCallback(getActivity()) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d("SortDetailFragment", s);
                        SubMitModel subMitModel = GsonUtil.GsonToBean(s, SubMitModel.class);
                        Toast.makeText(getActivity(), subMitModel.getMessage() + "", Toast.LENGTH_SHORT).show();


                    }
                });


            }
        });
        return view;
    }

    List<String> applyList = new ArrayList<>();
    String date_Send;

    @Override
    public void onItemClickListener(View view, int pos, List<ShopListModel.DataBean> myLiveList) {
        switch (view.getId()) {
            case R.id.checkbox:
                if (myLiveList.get(pos).getApplyAmount() == 0) {
                    Toast.makeText(getActivity(), "请选择商品数量", Toast.LENGTH_SHORT).show();
                    myLiveList.get(pos).setChecked(false);

                } else {
                    for (ShopListModel.DataBean cart : data) {
                        if (cart.isChecked()) {   //是否勾上去了
//                sum += cart.getCount() * cart.getPrice();
//                        sum += cart.getApplyAmount() * 10;
                            Log.d("勾选上了", "勾选上了");

                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("commodityId", cart.getCommodityId());
                                jsonObject.put("commodityAmount", cart.getApplyAmount() + "");
                                jsonObject.put("categoryId", "0");
                                jsonObject.put("mark", cart.getMark());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            applyList.add(jsonObject.toString());
                            ToolList.removeDuplicateWithOrder(applyList);
                            tv_total.setText("已选购" + applyList.size() + "");

                            Log.d("applyListapplyListapplyList", applyList.toString());

                        } else {
                            Log.d("取消勾选", "取消勾选");
                            if (applyList.size() > 0) {
                                for (int i = 0; i < applyList.size(); i++) {
                                    if (applyList.get(i).contains(cart.getCommodityId())) {
                                        applyList.remove(i);
                                    }
                                }
                            }
                            ToolList.removeDuplicateWithOrder(applyList);
                            Log.d("applyListapply", applyList.toString());
                            tv_total.setText("已选购" + applyList.size() + "");
                        }
                    }
                }


                break;

            case R.id.text_beizhu:

                MyLabelAdapter myLabelAdapter;
                LayoutInflater layoutInflater = LayoutInflater.from(getActivity());

                View view1 = layoutInflater.inflate(R.layout.dialog_bottom, null);

                ButtomDialogView bottomSheetDialog = new ButtomDialogView(getActivity(), view1, true, true);
                bottomSheetDialog.setContentView(R.layout.toast_dialog);
                bottomSheetDialog.show();
                RecyclerView recycle_biaoqian = view1.findViewById(R.id.recycle_biaoqian);
                GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 4);
                recycle_biaoqian.setLayoutManager(gridLayoutManager);

                myLabelAdapter = new MyLabelAdapter(getActivity());
                recycle_biaoqian.setAdapter(myLabelAdapter);
                List<String> mystr = new ArrayList<>();

                for (int i = 0; i < mVals.length; i++) {
                    mystr.add(mVals[i]);
                }
                myLabelAdapter.setDataList(mystr);
                DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
                divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.custom_divider));

                recycle_biaoqian.addItemDecoration(divider);
                ImageView img_close = view1.findViewById(R.id.img_close);
                img_close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                    }
                });
                myLabelAdapter.setOnItemClickListener(new MyLabelAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClickListener(View view, int pos, List<String> myLiveList) {

                    }
                });
                EditText verify_et = view1.findViewById(R.id.verify_et);

                TextView text_submit = view1.findViewById(R.id.text_submit);
                text_submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //为商品添加备注
                        HttpResponse.getRemark(token, myLiveList.get(pos).getCommodityId(), verify_et.getText().toString(), new StringCallback(getActivity()) {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                Log.d("SortDetaidkdkReturn", s);
                                BeiZhuModel beiZhuModel = GsonUtil.GsonToBean(s, BeiZhuModel.class);
                                Toast.makeText(getActivity(), beiZhuModel.getMessage(), Toast.LENGTH_SHORT).show();
                                myLiveList.get(pos).setMark(verify_et.getText().toString());
                                bottomSheetDialog.dismiss();
                                mAdapter.notifyDataSetChanged();
                            }
                        });

                    }
                });

                break;
        }
    }

    private String[] mVals = new String[]
            {"商品1", "商品2", "商品3 ", "商品4", "商品5", "商品6",
                    "商品7", "商品8"};



}
